package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.admin.service.LoginService;
import com.atguigu.lease.web.admin.service.SystemUserService;
import com.atguigu.lease.web.admin.vo.login.CaptchaVo;
import com.atguigu.lease.web.admin.vo.login.LoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate ;

    @Autowired
    private SystemUserService systemUserService ;

    @Override
    public CaptchaVo getCaptcha() {
        //定义验证码的尺寸以及字符数量
        SpecCaptcha specCaptcha = new SpecCaptcha(130,48,4);
        //设置纯数字
        specCaptcha.setCharType(Captcha.TYPE_ONLY_NUMBER);

        //获取验证码文本
        String captcha = specCaptcha.text();

        //1.将验证码内容保存到redis中(key-value)
        String key = RedisConstant.ADMIN_LOGIN_PREFIX+ UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(key,captcha, RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC, TimeUnit.SECONDS);

        //2.将验证码内容响应给客户端
        String img = specCaptcha.toBase64();


        return new CaptchaVo(img , key);
    }

    @Override
    public String login(LoginVo loginVo) {
        //1.前端发送过来的验证码为空，则登录失败
        if(!StringUtils.hasLength(loginVo.getCaptchaCode())){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_NOT_FOUND);
        }
        //2.前端发送过来的验证码和key，根据key去redis查询，为空则登录失败
        String key = loginVo.getCaptchaKey();
        String codeFromRedis = redisTemplate.opsForValue().get(key);
        if(!StringUtils.hasLength(codeFromRedis)){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }
        //3.比较前端发送过来的验证码和从redis中查出的验证码是否相同
        if(!loginVo.getCaptchaCode().equalsIgnoreCase(codeFromRedis)){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }
        //4.根据用户名去数据库查询对应的数据，如果查找不到则登录失败
        SystemUser systemUserFromDB = systemUserService.getOne(new LambdaQueryWrapper<SystemUser>().eq(SystemUser::getUsername,loginVo.getUsername()));
        if(systemUserFromDB==null){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        }
        //5.判断状态是否正常
        if(systemUserFromDB.getStatus()!= BaseStatus.ENABLE){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }
        //6.验证密码是否匹配（需要加密后再匹配）
        String yourPwd = DigestUtils.md5Hex(loginVo.getPassword());
        if(!yourPwd.equals(systemUserFromDB.getPassword())){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }
        //7.如果能够运行到这里，说明是合法用户，应该生成token
        String token = JwtUtil.createToken(systemUserFromDB.getId(),systemUserFromDB.getUsername());

        return token;
    }
}
